package com.ningxia.water.service.impl;

import com.ningxia.water.enums.JobStatusEnum;
import com.ningxia.water.configuration.quartz.QuartzManager;
import com.ningxia.water.entity.JobTask;
import com.ningxia.water.mapper.JobTaskMapper;
import com.ningxia.water.service.IJobTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hz
 * @since 2021-05-19
 */
@Service
public class JobTaskServiceImpl extends ServiceImpl<JobTaskMapper, JobTask> implements IJobTaskService {

    @Autowired
    private IJobTaskService jobTaskService;

    @Autowired
    QuartzManager quartzManager;


    /**
     * 初始化任务，从数据库中读取
     *
     * @throws SchedulerException
     */
    @Override
    public void initSchedule() throws SchedulerException {
        // 这里获取任务信息数据
        List<JobTask> jobList = jobTaskService.list();
        for (JobTask task : jobList) {
            if (JobStatusEnum.RUNNING.equals(task.getJobStatus())) {
                quartzManager.addJob(task);
            }
        }
    }


    @Override
    public boolean changeJobStatus(Integer id, String jobStatus) throws SchedulerException {
        JobTask jobTask = jobTaskService.getById(id);
        if (jobTask == null) return false;
        /**
         * 这里的删除不一样。
         * 如果任务已经在运行了，那么需要将任务从quartz中删除，然后修改任务状态
         * 如果任务不在运行，那么直接修改状态并添加到quartz
         */
        if (JobStatusEnum.STOP.getCode().equals(jobStatus)) {
            quartzManager.deleteJob(jobTask);

            jobTask.setJobStatus(JobStatusEnum.STOP.getCode());
        } else {
            jobTask.setJobStatus(JobStatusEnum.RUNNING.getCode());
            quartzManager.addJob(jobTask);
        }
        //更新数据库
        return jobTaskService.updateById(jobTask);
    }

    @Override
    public void run(JobTask jobtask) throws SchedulerException {
        quartzManager.runJobNow(jobtask);
    }

    @Override
    public boolean updateCronExpression(Integer jobId, String cronExpression) throws SchedulerException {
        JobTask jobTask = jobTaskService.getById(jobId);
        if (jobTask == null) {
            return false;
        }

        if (JobStatusEnum.STOP.getCode().equals(jobTask.getJobStatus())) {
            quartzManager.deleteJob(jobTask);
            jobTask.setCronExpression(cronExpression);
            jobTaskService.updateById(jobTask);
//            quartzManager.addJob(jobTask);
            return true;
        }
        return false;
    }

    @Override
    public boolean removeJobTask(Integer id) {
        try {
            JobTask jobTask = jobTaskService.getById(id);
            quartzManager.deleteJob(jobTask);
            return jobTaskService.removeById(id);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return false;
        }
    }
}
